<?php
namespace App\Services\Auth;
use App\Services\Captcha\ImagesCaptcha;
use App\Services\Helper;

/**
 * 账号密码登录验证
 *
 * @author: yanxs <541139655@qq.com>
 * @version: 1.0
 * @date: 2020/10/20
 */
class PasswordAuth implements AuthInterface
{
    protected $userRepository;
    protected $defaultUserRepository = NULL;

    /**
     * PasswordAuth constructor.
     */
    public function __construct()
    {

    }
    /**
     * 登录验证
     * @param 验证的字段 $authData
     * @return bool
     */
    public function verify($authData) : bool
    {
        //验证码验证
        if (config("common.captcha")['isOpen']) {
            $captchaCheck = app(ImagesCaptcha::class)->check($authData['captcha']);
            //验证码错误
            if (empty($captchaCheck)) {
                Helper::EasyThrowException('20032', __FILE__.__LINE__);
            }

        }

        if (empty($this->userRepository)) {
            return false;
        }

        //账号密码验证
        $res = $this->checkPassword($authData['username'], $authData['password']);
        if (!$res) {
            Helper::EasyThrowException('20003', __FILE__.__LINE__);
        }
        session(['admin'=> $res]);
        return true;
    }

    /**
     * 设置验证所需的数据仓库
     * @param $repository
     */
    public function setUserRepository($repository)
    {
        if (is_string($repository)) {
            $repository = app($repository);
        }
        $this->userRepository = $repository;
    }


    /**
     * 账号密码检查
     * @param $username
     * @param string $password
     * @return mixed
     */
    protected function checkPassword($username, $password='')
    {
        //验证账号密码是否正确
        $userRepository = $this->userRepository;
        //所有的账号仓库都得实现getInfoByUsername方法，否则会出错。
        $userInfo = $userRepository->getInfoByUsername($username);
        if (empty($userInfo)) {
            Helper::EasyThrowException('20003', __FILE__.__LINE__);
        }
        $md5Password = $this->md5Pwd($password,$userInfo['salt']);

        if ($md5Password !== $userInfo['password']) {
            return false;
        } else {
            return $userInfo;
        }

    }


    /**
     * md5加密
     * @param $password  明文密码
     * @param string $salt 盐值
     * @return string
     */
    public function md5Pwd($password, $salt = '')
    {
        return md5($password.$salt);
    }
}
